var path = require('path')
var dataJson = require(path.resolve('./area.json'))
var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'cabinet'
});

connection.connect();

function query(sql) {
	return new Promise((resolve, reject) => {
		connection.query(sql, function (error, results) {
		  if (error) throw error;
		  resolve(results)
		})
	})
}

//const districts = dataJson.districts[0].districts

function build(districts, parentId) {
	districts.forEach(async district => {
		const {name, code, level } = district
		console.log(name)
		const sql = `insert into district values (null, '${name}', '${code}', ${level}, ${parentId})`
		const res = await query(sql)
		if(district.districts && district.districts.length > 0) {
			build(district.districts, res.insertId)
		}
	})
}

build(dataJson.districts[0].districts, 0)